package com.atguigu.gmall.realtime.app.dws;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.atguigu.gmall.realtime.app.BaseApp;
import com.atguigu.gmall.realtime.bean.TrafficHomeDetailPageViewBean;
import com.atguigu.gmall.realtime.common.Constant;
import com.atguigu.gmall.realtime.util.AtguiguUtil;
import com.atguigu.gmall.realtime.util.FlinkSinkUtil;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.functions.ReduceFunction;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.KeyedProcessFunction;
import org.apache.flink.streaming.api.functions.windowing.ProcessAllWindowFunction;
import org.apache.flink.streaming.api.windowing.assigners.TumblingEventTimeWindows;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;
import org.apache.flink.util.Collector;

import java.time.Duration;

/**
 * @Author lzc
 * @Date 2023/1/7 08:27
 */
public class Dws_03_DwsTrafficPageViewWindow extends BaseApp {
    public static void main(String[] args) {
        new Dws_03_DwsTrafficPageViewWindow().init(
            4003,
            2,
            "Dws_03_DwsTrafficPageViewWindow",
            Constant.TOPIC_DWD_TRAFFIC_PAGE
        );
    }
    
    @Override
    public void handle(StreamExecutionEnvironment env,
                       DataStreamSource<String> stream) {
        // 1. 过滤详情页和首页,
        SingleOutputStreamOperator<JSONObject> homeAndGoodDetailStream = filterHomeAndGoodDetail(stream);
        // 2. 解析成 pojo 类型
        SingleOutputStreamOperator<TrafficHomeDetailPageViewBean> beanStream = parseToPojo(homeAndGoodDetailStream);
        // 2. 开窗聚合
        SingleOutputStreamOperator<TrafficHomeDetailPageViewBean> resultStream = windowAndAgg(beanStream);
        
        // 3. 写出到 clickhouse 中
        writeToClickHouse(resultStream);
    }
    
    private void writeToClickHouse(SingleOutputStreamOperator<TrafficHomeDetailPageViewBean> resultStream) {
        resultStream.addSink(FlinkSinkUtil.getClickHouseSink("dws_traffic_page_view_window", TrafficHomeDetailPageViewBean.class));
    }
    
    private SingleOutputStreamOperator<TrafficHomeDetailPageViewBean> windowAndAgg(
        SingleOutputStreamOperator<TrafficHomeDetailPageViewBean> beanStream) {
        return beanStream
            .windowAll(TumblingEventTimeWindows.of(Time.seconds(5)))
            .reduce(
                new ReduceFunction<TrafficHomeDetailPageViewBean>() {
                    @Override
                    public TrafficHomeDetailPageViewBean reduce(TrafficHomeDetailPageViewBean value1,
                                                                TrafficHomeDetailPageViewBean value2) throws Exception {
                        value1.setHomeUvCt(value1.getHomeUvCt() + value2.getHomeUvCt());
                        value1.setGoodDetailUvCt(value1.getGoodDetailUvCt() + value2.getGoodDetailUvCt());
                        return value1;
                    }
                },
                new ProcessAllWindowFunction<TrafficHomeDetailPageViewBean, TrafficHomeDetailPageViewBean, TimeWindow>() {
                    @Override
                    public void process(Context ctx,
                                        Iterable<TrafficHomeDetailPageViewBean> elements,
                                        Collector<TrafficHomeDetailPageViewBean> out) throws Exception {
                        TrafficHomeDetailPageViewBean bean = elements.iterator().next();
                    
                        bean.setStt(AtguiguUtil.tsToDateTime(ctx.window().getStart()));
                        bean.setEdt(AtguiguUtil.tsToDateTime(ctx.window().getEnd()));
                    
                        bean.setTs(System.currentTimeMillis());
                    
                        out.collect(bean);
                    }
                }
            );
    }
    
    private SingleOutputStreamOperator<TrafficHomeDetailPageViewBean> parseToPojo(
        SingleOutputStreamOperator<JSONObject> homeAndGoodDetailStream) {
        return homeAndGoodDetailStream
            .keyBy(obj -> obj.getString("mid"))
            .process(new KeyedProcessFunction<String, JSONObject, TrafficHomeDetailPageViewBean>() {
                
                private ValueState<String> homeLastVisitDateState;
                private ValueState<String> goodDetailLastVisitDateState;
                
                @Override
                public void open(Configuration parameters) throws Exception {
                    homeLastVisitDateState = getRuntimeContext().getState(new ValueStateDescriptor<String>("home", String.class));
                    goodDetailLastVisitDateState = getRuntimeContext().getState(new ValueStateDescriptor<String>("goodDetail", String.class));
                }
                
                @Override
                public void processElement(JSONObject obj,
                                           Context ctx,
                                           Collector<TrafficHomeDetailPageViewBean> out) throws Exception {
                    
                    String pageId = obj.getString("page_id");
                    Long ts = obj.getLong("ts");
                    
                    String today = AtguiguUtil.tsToDate(ts);
                    
                    Long homeUvCt = 0L;
                    Long goodDetailUvCt = 0L;
                    // 如果 home 页面, 再判断是否是第一个 home
                    if ("home".equals(pageId)) {
                        if (!today.equals(homeLastVisitDateState.value())) {
                            homeUvCt = 1L;
                            homeLastVisitDateState.update(today);
                            
                        }
                    } else {
                        // 是否是第一个 good_detail
                        if (!today.equals(goodDetailLastVisitDateState.value())) {
                            goodDetailUvCt = 1L;
                            goodDetailLastVisitDateState.update(today);
                        }
                    }
                    if (homeUvCt + goodDetailUvCt == 1) {
                        out.collect(new TrafficHomeDetailPageViewBean(
                            "", "",
                            homeUvCt, goodDetailUvCt,
                            ts
                        ));
                    }
                    
                }
            });
        
    }
    
    private SingleOutputStreamOperator<JSONObject> filterHomeAndGoodDetail(DataStreamSource<String> stream) {
        return stream
            .map(JSON::parseObject)
            .assignTimestampsAndWatermarks(
                WatermarkStrategy
                    .<JSONObject>forBoundedOutOfOrderness(Duration.ofSeconds(3))
                    .withTimestampAssigner((obj, ts) -> obj.getLong("ts"))
                    .withIdleness(Duration.ofSeconds(60))
            )
            .filter(obj -> {
                String pageId = obj.getString("page_id");
                
                return "home".equals(pageId) || "good_detail".equals(pageId);
                
            });
    }
}
/*
流量域页面浏览各窗口汇总表

    统计当日的首页和商品详情页独立访客数。
    
1. 数据源
    页面日志
2. 过滤出首页和详情页的日志记录

3. 独立访客
    keyBy -> mid
    
    需求两个状态: 分别记录首页的最后一次访问日期和
            详情页的最后一次访问日期
4. 开窗聚合
    不需要 keyBy
    
    windowAll
        窗口处理函数的并行度只能是 1
        
    

5. 写出
 */